import 'dart:async';

import 'package:flutter/material.dart';
import 'package:ok_github/page/route/route.dart';
import 'package:ok_ui/flutter_ok_ui.dart';

class RouteHelper {
  static Future<T> pushWidget<T>(
    BuildContext context,
    Widget widget, {
    bool replaceRoot = false,
    bool replaceCurrent = false,
  }) {
    return pushRoute(
      context,
      MaterialPageRoute<T>(builder: (ctx) => widget),
      replaceRoot: replaceRoot,
      replaceCurrent: replaceCurrent,
    );
  }

  static Future<T> pushRoute<T>(
    BuildContext context,
    PageRoute<T> route, {
    bool replaceRoot = false,
    bool replaceCurrent = false,
  }) {
    assert(!(replaceRoot == true && replaceCurrent == true));
    if (replaceRoot == true) {
      OKLog().log("replace root");
      try {
        return Navigator.pushAndRemoveUntil(
                context,
                route,
                _rootRoute,
              );
      } finally{
        routes.observer.replaceRoot(context);
      }
    }
    if (replaceCurrent == true) {
      return Navigator.pushReplacement(context, route);
    }
    return Navigator.push(context, route);
  }

  static Future<T> pushNamed<T>(
    BuildContext context,
    String name, {
    bool replaceRoot = false,
    bool replaceCurrent = false,
  }) {
    var widget = Navigator.of(context).widget;
    final RouteSettings settings = RouteSettings(
      name: name,
      isInitialRoute: replaceRoot,
    );
    Route<T> route = widget.onGenerateRoute(settings);
    if (route == null) {
      route = widget.onUnknownRoute(settings);
    }
    return pushRoute(
      context,
      route,
      replaceCurrent: replaceCurrent,
      replaceRoot: replaceRoot,
    );
  }

  static bool pop<T>(BuildContext context, [T result]) {
    return Navigator.pop(context, result);
  }
}


RoutePredicate get _rootRoute => ModalRoute.withName(routes.observer.rootName);
